package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class LeadController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def leadList
        def count
        if (UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_ADMINISTRATOR')) || UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_COMPANY_ADMINISTRATOR')))
        {
            leadList = Lead.findAll("from Lead where active = true order by createdDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
            count = Lead.executeQuery("select count(id) from Lead where active = true")
        }
        else
        {
            leadList = Lead.findAll("from Lead where user.username = '${username}' and active = true order by createdDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
            count = Lead.executeQuery("select count(id) from Lead where user.username = '${username}' and active = true")
        }

        respond leadList, model: [leadCount: count[0]]
    }

    def show(Lead lead)
    {
        Company company = Company.findAll()[0]
        Boolean enableTerritory = company.enableAccountTerritory

        def addressList = Address.findAll("from Address where lead.id = ?", [lead.id])
        def teamList = LeadTeam.findAll("from LeadTeam where lead.id = ?", [lead.id])
        def flexFieldInstanceList = FlexFieldInstance.findAll("from FlexFieldInstance where lead.id = ?", [lead.id])
        def attachmentList = Attachment.findAll("from Attachment where lead.id = ?", [lead.id])
        def noteList = Note.findAll("from Note where lead.id = ?", [lead.id])

        respond lead, model: [addressList: addressList, teamList: teamList, teamName: 'leadTeam', flexFieldInstanceList: flexFieldInstanceList, attachmentList: attachmentList, noteList: noteList, enableTerritory: enableTerritory]
    }

    def create()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        respond new Lead(params), model: [user: user]
    }

    @Transactional
    def save(Lead lead)
    {
        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (lead.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond lead.errors, view: 'create'
            return
        }

        lead.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'lead.label', default: 'Lead'), lead.id])
                redirect lead
            }
            '*' { respond lead, [status: CREATED] }
        }
    }

    def edit(Lead lead)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        TeamRole editTeamRole = TeamRole.findByName('Edit')
        LeadTeam leadTeam = LeadTeam.findByLeadAndUser(lead, user)

        if (lead?.user?.id == user?.id || leadTeam?.teamRole?.id == editTeamRole?.id)
        {
            respond lead, model: [user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect uri: request.getHeader("referer")
            // respond lead, view: 'show'
        }
    }

    @Transactional
    def update(Lead lead)
    {
        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (lead.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond lead.errors, view: 'edit'
            return
        }

        lead.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'lead.label', default: 'Lead'), lead.id])
                redirect lead
            }
            '*' { respond lead, [status: OK] }
        }
    }

    @Transactional
    def delete(Lead lead)
    {

        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        lead.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'lead.label', default: 'Lead'), Lead.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'lead.label', default: 'Lead'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchLead()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]
        def department = params["department"]
        def owner = params["owner"]
        def rating = params["rating"]
        def status = params["status"]
        def startTime = params["startTime"]
        def endTime = params["endTime"]

        String sql = "from Lead as u where u.active = true"

        if (!UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_ADMINISTRATOR')) && !UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_COMPANY_ADMINISTRATOR')))
        {
            sql += " and u.user.username='${username}'"
        }
        else
        {
            if (department)
            {
                sql += " and u.user.department.name like '%${department}%'"
            }
            if (owner)
            {
                sql += " and u.user.fullName like '%${owner}%'"
            }
        }

        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (rating)
        {
            sql += " and u.rating.name like '%${rating}%'"
        }
        if (status)
        {
            sql += " and u.status.name like '%${status}%'"
        }
        if (startTime)
        {
            sql += " and u.modifiedDate > '${startTime}'"
        }
        if (endTime)
        {
            sql += " and u.modifiedDate < '${endTime}'"
        }

        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Lead.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Lead.executeQuery(countSql)

        def lead = new Lead(params)
        respond list, model: [leadList: list, leadCount: count[0], lead: Lead, params: params], view: 'index'
    }

    @Transactional
    def exportLead()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]
        def company = params["company"]

        String sql = "from Lead as u where 1=1 and u.user.username = '${username}' and u.active = true"
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone like '%${cellphone}%'"
        }
        if (company)
        {
            sql += " and u.company.id = ${company}"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Lead.findAll(sql)
        def count = Lead.executeQuery(countSql)
        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=lead.${params.extension}")
            List fields = ["company", "numberOfEmployees", "industry.name", "website", "address", "rating.name", "status.name", "fullName", "salutation", "title", "email", "cellphone", "phone", "description", "createdDate", "modifiedDate"]
            Map labels = ["company": "公司名称", "numberOfEmployees": "人数", "industry.name": "行业", "website": "网站", "address": "地址", "rating.name": "评级", "status.name": "状态", "fullName": "姓名", "salutation": "称谓", "title": "头衔", "email": "邮件", "cellphone": "手机", "phone": "座机", "description": "线索描述", "createdDate": "创建时间", "modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }

    def changeToOpportunity(Lead lead)
    {
        Company company = Company.findAll()[0]
        Boolean enableTerritory = company.enableAccountTerritory

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        respond lead, model: [enableTerritory: enableTerritory, user: user]
    }

    @Transactional
    def changeToOpportunitySave(Lead lead)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def enableTerritory = params['enableTerritory']
        def territoryName = params["territoryName"]
        if (enableTerritory == "true" && !territoryName)
        {
            flash.message = "请选择销售区域"
            respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
            return
        }
        def accountId = params["accountId"]
        def accountName = params["accountName"]
        def accountType = params["accountType"]
        def website = params["website"]
        def parent = params["parent"]
        def industry = params["industryName"]
        def numberOfEmployees = params["numberOfEmployees"]

        def contactNameList = params["contactName"]
        def salutationList = params["salutationName"]
        def cellphoneList = params["cellphone"]
        def phoneList = params["phone"]
        def titleList = params["title"]
        def emailList = params["email"]

        if (contactNameList instanceof String)
        {
            params.type = "string"
            lead.fullName = contactNameList
            lead.salutation = Salutation.findByName(salutationList)
            lead.title = titleList
            lead.email = emailList
            lead.cellphone = cellphoneList
            lead.phone = phoneList
        }
        else
        {
            params.type = "list"
            if (contactNameList?.size() > 0)
            {
                lead.fullName = contactNameList[0]
            }
            if (salutationList?.size() > 0)
            {
                lead.salutation = Salutation.findByName(salutationList[0])
            }
            if (titleList?.size() > 0)
            {
                lead.title = titleList[0]
            }
            if (emailList?.size() > 0)
            {
                lead.email = emailList[0]
            }
            if (cellphoneList?.size() > 0)
            {
                lead.cellphone = cellphoneList[0]
            }
            if (phoneList?.size() > 0)
            {
                lead.phone = phoneList[0]
            }
        }


        Account account

        if (accountId)
        {
            account = Account.findById(accountId)
        }
        else
        {
            if (!accountName)
            {
                flash.message = "请输入客户姓名"
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }

            if (!accountType)
            {
                flash.message = "请输入客户类型"
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }

            account = Account.findByName(accountName)
            if (!account)
            {
                account = new Account()
                account.name = accountName
            }

            if (Territory.findByName(territoryName))
            {
                account.territory = Territory.findByName(territoryName)
            }

            account.type = AccountType.findByName(accountType)
            account.parent = Account.findById(parent)
            account.website = website
            account.industry = Industry.findByName(industry)
            account.numberOfEmployees = numberOfEmployees?.toInteger()

            if (account.validate())
            {
                account.save flush: true
            }
            else
            {
                println account.errors
                flash.message = "转换商机失败，请检查客户信息是否完善"
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }
        }


        def length = contactNameList?.size()
        def flag = true
        if (contactNameList instanceof String)
        {
            if (!contactNameList)
            {
                flash.message = "请输入联系人姓名"
                flag = false
            }
            if (!cellphoneList)
            {
                flash.message = "请输入联系人手机号"
                flag = false
            }
            if (Contact.findByCellphone(cellphoneList))
            {
                flash.message = "转换商机失败，联系人" + cellphoneList + "已被登记"
                flag = false
            }

            if (!flag)
            {
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }

            Contact contact = new Contact()
            contact.account = account
            contact.type = ContactType.findByName("日常联系人")
            contact.fullName = contactNameList
            contact.salutation = Salutation.findByName(salutationList)
            contact.cellphone = cellphoneList
            contact.phone = phoneList
            contact.title = titleList
            contact.email = emailList

            if (contact.validate())
            {
                contact.save()
            }
            else
            {
                println contact.errors
                flag = false
                flash.message = "转换商机失败，请检查客户信息是否完善"
            }
            if (!flag)
            {
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }
        }
        else
        {
            for (
                def i = 0;
                    i < length;
                    i++)
            {
                if (contactNameList?.size() < i + 1)
                {
                    flash.message = "请输入联系人姓名"
                    flag = false
                    break
                }
                if (cellphoneList?.size() < i + 1)
                {
                    flash.message = "请输入联系人手机号"
                    flag = false
                    break
                }
                if (Contact.findByCellphone(cellphoneList[i]))
                {
                    flash.message = "转换商机失败，联系人" + cellphoneList[i] + "已被登记"
                    flag = false
                    break
                }
            }

            if (!flag)
            {
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }
            for (
                def i = 0;
                    i < length;
                    i++)
            {
                Contact contact = new Contact()
                contact.account = account
                contact.type = ContactType.findByName("日常联系人")
                if (contactNameList?.size() >= i + 1)
                {
                    contact.fullName = contactNameList[i]
                }
                if (salutationList?.size() >= i + 1)
                {
                    contact.salutation = Salutation.findByName(salutationList[i])
                }
                if (cellphoneList?.size() >= i + 1)
                {
                    contact.cellphone = cellphoneList[i]
                }
                if (phoneList?.size() >= i + 1)
                {
                    contact.phone = phoneList[i]
                }
                if (titleList?.size() >= i + 1)
                {
                    contact.title = titleList[i]
                }
                if (emailList?.size() >= i + 1)
                {
                    contact.email = emailList[i]
                }

                if (contact.validate())
                {
                    contact.save()
                }
                else
                {
                    println contact.errors
                    flag = false
                    flash.message = "转换商机失败，请检查客户信息是否完善"
                    break
                }
            }

            if (!flag)
            {
                respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
                return
            }
        }

        Opportunity opportunity = new Opportunity()
        opportunity.lead = lead
        opportunity.account = account
        opportunity.status = OpportunityStatus.findByName("跟进中")
        opportunity.productLine = ProductLine.findById(params["productLine"])
        opportunity.product = Product.findById(params["product"])
        if (opportunity.validate())
        {
            opportunity.save flush: true
        }
        else
        {
            println opportunity.errors
            flash.message = "转换商机失败，请检查线索信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
            return
        }

        lead.active = false

        if (lead.validate())
        {
            lead.save flush: true
        }
        else
        {
            println lead.errors
            flash.message = "转换商机失败，请检查线索信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user, params: params], view: 'changeToOpportunity'
            return
        }

        redirect controller: 'opportunity', action: "index"
    }
}
